package com.example.book.interceptor;

import com.example.book.constant.Constants;
import com.example.book.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;


@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper=new ObjectMapper();
    //直接按pre就可以直接生成
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //true--放行  false--拦截
        //log.info("执行preHandle...");
        log.info("登录拦截...");
        HttpSession session= request.getSession(false);
        if (session==null||session.getAttribute(Constants.SESSION_USER_KEY) == null ||
                !StringUtils.hasLength((String) session.getAttribute(Constants.SESSION_USER_KEY))) {
            //返回空的话，证明用户未登录
            log.error("用户未登录，进行拦截");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            Result result=Result.unlogin();
            //response.getOutputStream().write("{\"ok\":false}".getBytes());
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());
            response.setContentType("application/json;charset=utf-8");
            return false;
        }
        log.info("用户登录校验通过");
        return true;
        //return HandlerInterceptor.super.preHandle(request, response, handler);
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("执行postHandle");
//        //HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("执行afterCompletion");
//        //HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
